// ============================================================ //
// ============================================================ //
//
// @Group       : QiXin Supply Chain Team
// @Author      : ZhiQiang Cheng
// @Date        : 2024-07-11
// @Description : 房间通知列表: 每次开团, 结束的时候发送一个更新信号.
//
// ============================================================ //
// ============================================================ //

package job

import (
	"sync/atomic"
	"time"
	"wooha-cache-hub/cache"
	"wooha-cache-hub/dao"

	"github.com/StarfishProgram/starfish-go-sdk/sdklog"
	"github.com/StarfishProgram/starfish-go-sdk/sdktypes"
)

type roomNotice struct{}

var RoomNotice = new(roomNotice)

func (rn *roomNotice) Listen(running *atomic.Bool) {
	for running.Load() {
		roomId, err := cache.PopRoomNoticeChannel()
		if err != nil {
			sdklog.Error(err)
			time.Sleep(time.Second)
			continue
		} else if roomId == nil {
			time.Sleep(time.Second)
			continue
		}

		sdklog.Info("房间通知频道:", roomId)
		rn.handle(*roomId)
	}
}

func (r *roomNotice) handle(roomId sdktypes.ID) {
	notices, err := dao.GroupBuyingRoomNotice.GetByRoomId(roomId, 300)
	if err != nil {
		sdklog.Error(err)
		return
	} else if len(notices) == 0 {
		sdklog.Error("房间通知不存在:", roomId)
		return
	}

	if err := cache.FlushRoomNotice(roomId, notices); err != nil {
		sdklog.Error(err)
		return
	}

	sdklog.Info("房间通知已刷新:", roomId)

}
